import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

// 初始化的时候从缓存中读取状态 并赋值到初始化的状态上
// Vuex的持久化 如何实现 ？ Vuex和前端缓存相结合
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },

  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 定义方法调用接口请求数据
  async login(context, data) {
    const result = await login(data)

    context.commit('setToken', result)
    setTimeStamp() // 将当前的最新时间写入缓存
  },

  async getUserInfo(context, data) {
    const result = await getUserInfo()

    const baseInfo = await getUserDetailById(result.userId)

    const baseResult = { ...result, ...baseInfo } // 将两个接口结果合并

    console.log(baseResult)
    context.commit('setUserInfo', baseResult)
    return result
  },

  logout(context) {
    context.commit('removeToken')

    context.commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
